
const Controller = require('../../core/Controller');
const TopClient = require('../../topClient').TopClient;
const query = require('../../core/db');
let sessionCode = null;

class couponController extends Controller {
  constructor() {
    super();
  }

//  async getGoodsList(ctx) {
//  let sql = 'select * from goods where 1=1';
//  let values = [];
//  ctx.response.body = await query(sql, values).then( results => { return results; });
//}

  async getSession(ctx) {
    const { code } =  ctx.request.body || ctx.request.query;
    console.log('code', code);
    var client = new TopClient({
      'appkey': '24543960',
      'appsecret': '1bfaf3acf176650779faf3bb465acc9d',
      //'REST_URL': 'https://gw.api.taobao.com/router/rest'
      url: 'https://eco.taobao.com/router/rest'
    });

    let session = await new Promise(( resolve, reject ) => {
      client.execute('taobao.top.auth.token.create', {code}, function(error, response) {
        if (!error) {
          console.log(response);
          resolve(response)
        } else {
          console.log('taobao.top.auth.token.create ===== error ======', error);
          resolve(error)
        }
      })
    }).then(res => {
        console.log('res', res);
//return res;
        if(res.token_result) {
          let tokenRes = JSON.parse(res.token_result);
          sessionCode = tokenRes.access_token;
          return tokenRes.access_token;
        } else {
          return res;
        }
      });
    console.log('session', session);
    ctx.response.body = session;
  }

  async getAllGoodsList(ctx) {
    const { q = '', order_by = 'list_time:desc' } =  ctx.request.body || ctx.request.query;
    var client = new TopClient({
      'appkey': '24543960',
      'appsecret': '1bfaf3acf176650779faf3bb465acc9d',
      'REST_URL': 'http://gw.api.taobao.com/router/rest'
    });

    let response = await new Promise(( resolve, reject ) => {
      client.execute('taobao.items.onsale.get', {
        'fields':'approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id,sold_quantity',
        q, order_by, session: sessionCode
      }, function(error, response) {
        if (!error) {
          console.log(response);
          resolve(response);
        } else {
          console.log('taobao.items.onsale.get ===== error ======',error);
        }
      });
    }).then(res => {
        return res;
      });
    response.sssss = sessionCode;
    ctx.response.body = response;
  }

  async addGoods(ctx) {
    const { p_id, g_num, g_title, g_price, g_imgUrl } =  ctx.request.body || ctx.request.query;
    console.log( p_id, g_num, g_title, g_price, g_imgUrl);
    await new Promise((resolve, reject) => {

    });
    let sql = 'select * from goods where 1=1';
    let values = [];
    ctx.response.body = true;
  }
}

module.exports = new couponController;
